Strict
Import "bluecc_inc.bmx"

TType.create_primitives


Type TModule
	Global list:TModule[], Main:TModule
	Global Current:TModule
	Global types:TType[]
	Global globvars:TVariable[]
	Global functions:TFunction[]
	Global undefined:TIdentifier

	Field name:String
	Field path:String

	Function add(name:String, path:String)
		Local m:TModule = New TModule
		m.name = name ; m.path = path
		list :+ [m]
		If Not Main Then Main = m
	EndFunction
	
	Function find_type:TType(s:String)
		Local t:TType
		s = s.tolower()
		For t = EachIn types
			If t.name.tolower() = s Then Return t
		Next
		Return Null
	EndFunction
EndType

Type TIdentifier
	Field name:String
	Field realname:String
	Field typ:TType
	
	Field modul:TModule, line ' <- error messages
	
	Method New()
		modul = TModule.Current
		line = vline
	EndMethod
	
EndType

Type TType Extends TIdentifier
	
	
	Global primitives:TType[]
	Global t_int:TType, t_long:TType, t_double:TType
	
	Function Create:TType(name:String, realname:String = "", supertyp:TType = Null)
		Local t:TType = New TType
		t.name = name
		t.realname = realname
		t.typ = supertyp
		Return t
	EndFunction
	
	Function find:TType(s:String)
		Return TModule.find_type(s)
	EndFunction
	
	Function create_primitives()
		t_int= Create("Int", "int")
		t_long = Create("Long", "long long")
		t_double = Create("Double", "double")
		primitives = [t_int, t_long, t_double]
		TModule.types :+ primitives
	EndFunction
	
	Method is_primitive()
		Local t:TType
		For t = EachIn primitives
			If t = Self Then Return True
		Next
		Return False
	EndMethod

EndType

Type TVariable Extends TIdentifier

	Field pointer

	Function parse:TVariable[]()
		Local a:TVariable[], s:String, v:TVariable
		Repeat
			v = New TVariable
			v.name = getname()
			
			v.realname = "bb_"+v.name ' for now
			
			skipblanks
			If look = Asc ":" Then
				GetChar
				s = getname()
				v.typ = TType.find(s.tolower())
				If Not v.typ Then error "type '"+s+"' not found"
				skipblanks
			Else
				v.typ = TType.t_int
			EndIf
			While low(look) = Asc "p"
				s = getname().tolower()
				If s <> "ptr" Then error "unexpected TIdentifier "+s
				v.pointer :+ 1
			Wend
			a :+ [v]
			If look <> Asc(",") Then Exit
			GetChar
			skipwhite
		Forever
		
		Return a
	EndFunction
	
	Function parse_local()
	
	EndFunction 
	
	Function parse_global() 
		TModule.globvars :+ parse()
	EndFunction 

EndType


Type TFunction Extends TIdentifier
	
EndType

